package com.youbug.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youbug.system.entity.LoginLog;
import com.youbug.system.entity.User;
import com.youbug.system.mapper.LoginLogMapper;
import com.youbug.system.service.ILoginLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youbug.common.util.IPUtils;
import com.youbug.system.vo.LoginLogVo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

/**
 * <p>
 * 登录日志 服务实现类
 * </p>
 *
 * @author youbug
 * @since 2023-05-06
 */
@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements ILoginLogService {

    @Override
    public void saveLog(HttpServletRequest request, User user) {
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(user.getUsername());
        loginLog.setNickName(user.getNickName());
        loginLog.setLoginTime(LocalDateTime.now());
        loginLog.setIpAddress(IPUtils.getIpAddress(request));
//        loginLog.setIpArea();
        this.save(loginLog);
    }

    @Override
    public IPage<LoginLog> getLoginLogPage(LoginLogVo vo) {

        Page<LoginLog> pageParam = new Page<>();

        pageParam.setCurrent(vo.getCurrentPage());

        pageParam.setSize(vo.getPageSize());

        QueryWrapper<LoginLog> wrapper = new QueryWrapper<>();

        if(!ObjectUtils.isEmpty(vo.getBeginTime())){

            wrapper.gt("login_time", vo.getBeginTime());
        }

        if(!ObjectUtils.isEmpty(vo.getEndTime())){

            wrapper.lt("login_time", vo.getEndTime());
        }

        wrapper.orderByDesc("login_time");

        Page<LoginLog> page = this.page(pageParam, wrapper);

        return page;
    }
}
